﻿using MediatR;
using Traceability.App.API.Application.Command.BasicTraceability;
using Traceability.App.Domain.Traceability;
using Traceability.App.ErrorCode;
using Traceability.App.Infrastructrue.Interface;

namespace Traceability.App.API.Application.Handler.BasicTraceability
{
    public class DelBasicTracebilityHandler : IRequestHandler<DelBasicTracebilityCommand, APIResult<int>>
    {
        private readonly IBaseRepository<BasicTraceabilityModel> basicRepo;

        public DelBasicTracebilityHandler(IBaseRepository<BasicTraceabilityModel> basicRepo)
        {
            this.basicRepo = basicRepo;
        }

        public Task<APIResult<int>> Handle(DelBasicTracebilityCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result = new APIResult<int>();
            var list = request.Id.Split(',').Select(x => Convert.ToInt32(x)).ToList();
            int r = 0;
            foreach (var item in list)
            {
                var res = basicRepo.GetAll().FirstOrDefault(x => x.Id == item);
                res.IsDel = true;
                r = basicRepo.UpdateAsync(res).Result;
            }
            if (r > 0)
            {
                result.Message = "删除成功";
                result.Code = APIEnum.Ok;
                result.Data = r;
            }
            else
            {
                result.Message = "删除失败";
                result.Code = APIEnum.Fail;
                result.Data = r;
            }
            return Task.FromResult(result);
        }
    }
}
